<template>
  <img
    v-if="data.src"
    :style="{
      width: props.style.width,
      height: props.style.height
    }"
    :src="data.src"
    alt=""
  />
</template>

<script setup lang="ts">
import { watchEffect } from 'vue'
import QRCode from 'qrcode'
import type { IDiyBase } from '@/diy/types'
import { useVModel } from '@vueuse/core'
import { debounce } from 'lodash-es'

const props = defineProps<IDiyBase>()

const emit = defineEmits(['update:data'])

const data = useVModel(props, 'data', emit)

const _generateQR = async ({ text, margin }: any) => {
  try {
    console.log(text, 'text')
    data.value.src = await QRCode.toDataURL(text, {
      margin
    })
  } catch (err) {
    console.error(err)
  }
}

const generateQR = debounce(_generateQR, 200)

watchEffect(() => {
  const { text, margin } = data.value
  generateQR({
    text,
    margin
  })
})
</script>

<style scoped></style>
